package polep.wespace.schedule;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import polep.wespace.model.WeChatPublicNumber;
import polep.wespace.service.WeChatPublicNumberService;
import polep.wespace.utils.HttpClientUtil;
import polep.wespace.utils.Utils;

@Component(value="accessToken")
public class GetAccessToken {
	private Log log = LogFactory.getLog(GetAccessToken.class);
	@Resource(name="wechatPublicNumberService")
	private WeChatPublicNumberService weChatPublicNumberService;
	@Scheduled(cron="0 0 0/2 * * ?")
	@PostConstruct
	public void getAccessToken(){
		WeChatPublicNumber weChatPublicNumber = weChatPublicNumberService.getFirstWeChatPublicNumber();
		if( weChatPublicNumber != null ){
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
			String urln = url.replace("APPID", weChatPublicNumber.getAppId()).replace("APPSECRET", weChatPublicNumber.getAppSecret());
			String respStr = HttpClientUtil.doGet(urln.trim());
			Map respMap = Utils.jsonStr2Map(respStr);
			weChatPublicNumber.setAccessToken((String)respMap.get("access_token"));
			weChatPublicNumberService.updateAccessToken(weChatPublicNumber);
			log.info("ACCESS_TOKEN update success!");
		}else{
			log.info("wechatPublicNumber is null");
		}
		
		
	}
}
